import { defineStore } from 'pinia'
import { request } from '@/utils/request'

// const token = 'pat_hDLUMqRTuu6iyZo25QTCKqK07KkRwh6JiQiroJZSUqdKlDnwrMF6PE1LI5POPB70'

export const useContentStore = defineStore('content', {
    state: () => ({
        contents: [],
        contentTypes: ['全部', '文字', '媒体', '链接'],
        contentTypeMap: {
            '全部': '',
            '文字': 'text',
            '媒体': 'image',
            '链接': 'link'
        },
        loading: false
    }),

    actions: {
        // 添加获取内容详情的方法
        async fetchContentDetail(id) {
            try {
                const response = await request.get(`/contents/${id}`)
                console.log("response", response)
                return response.data
            } catch (error) {
                console.error('获取内容详情失败:', error)
                throw error
            }
        },

        async fetchContents(obj = {}) {
            console.log("obj", obj)
            const { type, page = 1, pageSize = 10 } = obj
            this.loading = true
            try {
                const typeId = type ? this.contentTypeMap[type] : null
                const url = typeId 
                    ? `/contents?type=${typeId}&page=${page}&pageSize=${pageSize}` 
                    : `/contents?page=${page}&pageSize=${pageSize}`
                const { data } = await request.get(url)
                return {
                    items: data.list || [],
                    total: data.total,
                    hasMore: (data.list || []).length === pageSize
                }
            } catch (error) {
                console.error('获取内容列表失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        async createContent(content) {
            try {
                const { data } = await request.post('/contents', content)
                this.contents.unshift(data)
                return data
            } catch (error) {
                console.error('创建内容失败:', error)
                throw error
            }
        },

        async updateContent(content) {
            try {
                const { data } = await request.put(`/contents/${content.id}`, content)
                const index = this.contents.findIndex(item => item.id === content.id)
                if (index !== -1) {
                    this.contents[index] = data
                }
                return data
            } catch (error) {
                console.error('更新内容失败:', error)
                throw error
            }
        },

        async deleteContent(contentId) {
            try {
                await request.delete(`/contents/${contentId}`)
                this.contents = this.contents.filter(item => item.id !== contentId)
            } catch (error) {
                console.error('删除内容失败:', error)
                throw error
            }
        }
    }
})